package com.yuzhantao.collection.sensorflow.response.handle;

import org.jboss.logging.Logger;

import com.alibaba.fastjson.JSON;
import com.yuzhantao.collection.core.message.IMessageHandle;
import com.yuzhantao.collection.sensorflow.message.SensorFlowMessage;
import com.yuzhantao.collection.sensorflow.model.UInfo;
import com.yuzhantao.collection.sensorflow.model.UInfoRepository;

public class InsertTagHandle implements IMessageHandle<SensorFlowMessage, Object> {
	protected static final Logger logger = Logger.getLogger(InsertTagHandle.class);
	protected final static String SAMPLE_UNIT_ID_PATTERN = "^(tag\\-)[0-9]";
	protected final static String CHANNEL_ID = "asset";
	private UInfoRepository uInfoRepository;

	public InsertTagHandle(UInfoRepository uInfoRepository) {
		this.uInfoRepository = uInfoRepository;
	}

	@Override
	public boolean isHandle(SensorFlowMessage t) {
//		if (Pattern.matches(SAMPLE_UNIT_ID_PATTERN, t.getSampleUnitId()) && CHANNEL_ID.equals(t.getChannelId())) {
		if (this.isVail(t.getSampleUnitId()) && CHANNEL_ID.equals(t.getChannelId())) {
			return true;
		} else {
			return false;
		}
	}

	private boolean isVail(String sampleUnitId) {
		return sampleUnitId.indexOf("tag") == 0;
	}

	@Override
	public Object handle(SensorFlowMessage t) {
//		Preconditions.checkNotNull(t.getValue());
		int uPosition = Integer.valueOf(t.getSampleUnitId().replaceAll("tag-", ""));
		// TODO 由于川师大u位硬件顺序颠倒，顾写顺序修正
		uPosition = 42 - uPosition + 1;
		
		String deviceCode = t.getMonitoringUnitId();
		String tag = String.valueOf(t.getValue());
		tag = tag.substring(3, tag.length());
		UInfo uInfo = uInfoRepository.findOneByTag(tag);
		if (uInfo == null) {
			uInfo = new UInfo();
		}
		uInfo.setDeviceCode(deviceCode);
		uInfo.setPosition(uPosition);
		uInfo.setTag(tag);
		uInfoRepository.saveAndFlush(uInfo);
		logger.info("获取到U位变化，并保存到本地数据库中:" + JSON.toJSONString(uInfo));
		return null;
	}

}
